<?php
/**
 *   Joomdiet - administrator/components/models/recipe.php
 *   Author: Juan Dapena Paz (juan@bittingbits.com)
 *   Copyright (C) 2011 Bitting Bits S.L.
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');
class JoomdietModelRecipe extends JModel
{
    var $_data;
    var $_recipe;
    var $_pagination;
    
    function __construct()
    {
        parent::__construct();
        global $mainframe, $option;
        
        try {
            $array = JRequest::getVar('cid', 0, '', 'array');
            $this->setId((int)$array[0]);
        } catch (Excepcion $e) {
            // do nothing
        }
        
        // loading pagination support
        $limit = $mainframe->getUserStateFromRequest('global.list.limit',
                                                     'limit',
                                                     $mainframe->getCfg('list_limit'),
                                                     'int');
        $limitstart = JRequest::getVar('limitstart', 0, '', 'int');
        $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
        $this->setState('limit', $limit);
        $this->setState('limitstart', $limitstart);
    }
    
    // default query constructor
    function _buildQuery() {
        $query = 'SELECT * FROM #__joomdiet_Recipes';
        return $query;
    }
    
    function setId($id) {
        $this->_id = $id;
        $this->_data = null;
        $this->_recipe = null;
    }
    
    function getData()
    {
        if (empty($this->_data)) {
            $query = $this->_buildQuery();
            if (empty($this->_pagination)) {
                $this->_data = $this->_getList($query);
            } else {
                $this->_data = $this->_getList($query, 
                                               $this->getState('limitstart'),
                                               $this->getState('limit'));
            }
            if (empty($this->_data)) $this->_data = array();
        }
        
        return $this->_data;
    }
    
    function getPagination()
    {
        if (empty($this->_pagination)) {
            jimport('joomla.html.pagination');
            $this->_pagination = new JPagination($this->getTotal(),
                                                 $this->getState('limitstart'),
                                                 $this->getState('limit'));
        }
        
        return $this->_pagination;
    }
    
    function getTotal()
    {
        if (empty($this->_total)) {
            $query = $this->_buildQuery();
            $this->_total = $this->_getListCount($query);
        }
        return $this->_total;
    }
    
    function getRecipe()
    {
        if ($this->_loadRecipe()) {
        } else $this->_initRecipe();
        
        return $this->_recipe;
    }
    
    function _loadRecipe()
    {
        if (empty($this->_recipe)) {
            $query = 'SELECT * FROM #__joomdiet_Recipes'.
                ' WHERE id='.$this->_id;
            $this->_db->setQuery($query);
            $this->_recipe = $this->_db->loadObject();
        }
        
        return (boolean) $this->_recipe;
    }
    
    function _initRecipe()
    {
        if (empty($this->_recipe)) {
            $recipe = new stdClass();
            $recipe->id = 0;
            $recipe->name = null;
            $recipe->description = null;
            $recipe->recipe_category_id = null;
            
            $this->_recipe = $recipe;
            return (boolean) $this->_recipe;
        }
        
        return true;
    }
    
    function store()
    {
        $this->getRecipe();
        
        $this->_recipe->name = JRequest::getVar('recipe_name');
        $this->_recipe->description = JRequest::getVar('recipe_description');
        $this->_recipe->recipe_category_id = JRequest::getVar('recipe_parent_category');
        $this->_recipe->id = JRequest::getVar('recipe_id');
        
        if (!$this->_recipe->id) {
            $query = 'INSERT INTO #__joomdiet_Recipes'.
                ' (name, description, recipe_category_id)'.
                ' VALUES ("'.$this->_recipe->name.'",'.
                ' "'.$this->_recipe->description.'",'.
                ' '.$this->_recipe->recipe_category_id.')';
        } else {
            $query = 'UPDATE #__joomdiet_Recipes'.
                ' SET name="'.$this->_recipe->name.'",'.
                ' description="'.$this->_recipe->description.'",'.
                ' recipe_category_id='.$this->_recipe->recipe_category_id.
                ' WHERE id='.$this->_recipe->id;
        }
        
        $this->_db->setQuery($query);
        $this->_db->query();
        
        if (!$this->_recipe->id) {
            return $this->_db->insertid();
        } else return $this->_recipe->id;
    }
    
    function delete($id)
    {
        // deleting food
        $query = 'DELETE FROM #__joomdiet_Recipe WHERE id='.$id;
        $this->_db->setQuery($query);
        $this->_db->query();
        
        // deleting food variables relations
        $query = 'DELETE FROM #__joomdiet_Recipe_food WHERE id_recipe='.$id;
        $this->_db->setQuery($query);
        $this->_db->query();
        
        return true;
    }
    
    function exists($id)
    {
        $query = 'SELECT count(*) FROM #__joomdiet_Recipe WHERE id='.$id;
        $this->_db->setQuery($query);
        return $this->_db->loadResult();
    }
    
    function add($recipe)
    {
        $query = 'INSERT INTO #__joomdiet_Recipe (name, description,';
        $query .= ' recipe_category_id) VALUES (';
        $query .= $recipe->name.', ';
        $query .= $recipe->description.', ';
        $query .= $recipe->recipe_category_id.')';
        
        $this->_db->setQuery($query);
        $this->_db->query();
        $recipe->id = $this->_db->insertid();
        
        if (count($recipe->sug_rels) > 0) {
            foreach ($recipe->food_rels as $key => $rel) {
                $query = 'INSERT INTO #__joomdiet_Recipe_food (id_recipe,';
                $query .= ' id_food, amount, unit) VALUE (';
                $query .= $recipe->id.', ';
                $query .= $key.', ';
                
                if ($rel != '') {
                    $rel_tokens = explode(' ', $rel);
                    
                    $query .= '"'.$rel_tokens[0].'", ';
                    if (count($rel_tokens) == 2) {
                        $query .= '"'.$rel_tokens[1].'")';
                    } else $query .= '"")';
                } else {
                    $query .= '"", "")';
                }
                
                $this->_db->setQuery($query);
                $this->_db->query();
            }
        }
    }
    
    function update($recipe)
    {
        $query = 'UPDATE #__joomdiet_Recipe SET name='.$recipe->name;
        $query .= ', description='.$recipe->description;
        $query .= ', recipe_category_id='.$recipe->recipe_category_id;
        $query .= ' WHERE id='.$recipe->id;
        
        $this->_db->setQuery($query);
        $this->_db->query();
        
        if (count($recipe->food_rels) > 0) {
            foreach ($recipe->food_rels as $key => $rel) {
                $query = 'SELECT count(*) FROM #__joomdiet_Recipe_food';
                $query .= ' WHERE id_recipe='.$recipe->id;
                $query .= ' AND id_food='.$key;
                
                $this->_db->setQuery($query);
                if ($this->_db->loadResult()) { // update row
                    $query = 'UPDATE #__joomdiet_Recipe_food SET';
                    if ($rel != '') {
                        $rel_tokens = explode(' ', $rel);
                        
                        $query .= ' amount="'.$rel_tokens[0].'", ';
                        if (count($rel_tokens) == 2) {
                            $query .= 'unit="'.$rel_tokens[1].'"';
                        } else $query .= 'unit=""';
                    } else $query .= ' amount="", unit=""';
                    
                    $query .= ' WHERE id_recipe='.$recipe->id;
                    $query .= ' AND id_food='.$key;
                } else { // insert new row
                    $query = 'INSERT INTO #__joomdiet_Recipe_food';
                    $query .= ' (id_recipe, id_food, amount, unit) VALUES (';
                    $query .= $recipe->id.', ';
                    $query .= $key.', ';
                    
                    if ($rel != '') {
                        $rel_tokens = explode(' ', $rel);
                        
                        $query .= '"'.$rel_tokens[0].'", ';
                        if (count($rel_tokens) == 2) {
                            $query .= '"'.$rel_tokens[1].'")';
                        } else $query .= '"")';
                    } else {
                        $query .= '"", "")';
                    }
                }
                
                $this->_db->setQuery($query);
                $this->_db->query();
            }
        }
    }
}
?>
